import "./index.css";
import { useState, useRef } from "react"
import { Modal, Checkbox, Form, Input, Button, message } from "antd"
import Uploader from "./Upload"
import * as api from "@/api/product"
const Dialog = (props) => {
    let { visible, handleGetCategory } = props;
    //上传之后的图片地址
    let [categoryImgurl, setCategoryImgurl] = useState("")

    //获取Form的实例
    let categoryForm = useRef(null)

    const onFinish = (values) => {
        console.log('Success:', values);
        // console.log('Failed:', errorInfo);
        if (!categoryImgurl) {
            //如果没有上传图片
            message.error('请上传类目图片')
        } else {
            //发起请求
            api.addCategory(values.categoryName, categoryImgurl)
                .then(res => {
                    console.log(res.data)
                    if (res.data.state) {
                        //添加成功
                        message.success('添加成功')
                        //更新列表 父组件传递下来的
                        handleGetCategory()
                    }
                })
        }
    };

    const onFinishFailed = (errorInfo) => {
        message.error('请传入类目的名称')
    };

    //上传图片之后,可以获取服务器返回的图片地址,通过此方法进行设置
    let handleSetCategoryImgurl = (imgUrl) => {
        setCategoryImgurl(imgUrl)
        console.log(imgUrl)
    }


    return (
        <Modal visible={visible} cancelText='取消' okText='确定' onOk={() => {
            props.onOk(categoryForm)
        }} onCancel={() => {
            props.onCancel()
        }}>
            <Form
                ref={categoryForm}
                name="basic"
                labelCol={{
                    span: 8,
                }}
                wrapperCol={{
                    span: 16,
                }}
                initialValues={{
                    remember: true,
                }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
            >
                <Form.Item
                    label='类目图片'
                    name='cagtegorPic'
                >
                    <Uploader onUpload={handleSetCategoryImgurl} />
                </Form.Item>
                <Form.Item
                    label="类目名称"
                    name="categoryName"
                    rules={[
                        {
                            required: true,
                            message: '输入类目的名称',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    )
}

export default Dialog;